﻿using Lanbt.Core.Entity;
using Lanbt.Core.Entity.Dto.lanbt_user;
using Lanbt.Core.Service.SqlService.IService;
using Lanbt.Core.Utility;
using Lanbt.Core.Utility.ExceptionExtent;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace Lanbt.Core.Service.SqlService
{
    public class ServiceBase
    {
        private readonly IHttpContextAccessor _contextAccessor;
        private readonly IUserService _userService;

        public ServiceBase()
        {
            _contextAccessor = GlobalContext.ServiceProvider.GetService<IHttpContextAccessor>();
            _userService = GlobalContext.ServiceProvider.GetService<IUserService>();
        }
        
        /// <summary>
        /// 获取当前用户信息
        /// </summary>
        public CurrentUser CurrentUser
        {
            get
            {
                if(_contextAccessor == null)
                {
                    return new CurrentUser();
                }
                return (CurrentUser)_contextAccessor.HttpContext?.User;
            }
        }

        /// <summary>
        /// 获取当前登录用户基本信息
        /// </summary>
        /// <returns></returns>
        /// <exception cref="LanbtException"></exception>
        public async Task<GetCurrentUserOutput> GetCurrentUserInfo()
        {
            var res = await _userService.GetUserById(CurrentUser.Id);
            if (!res.Success)
            {
                throw new LanbtException(ExceptionModel.EXCEPTION, "获取当前登录人失败");
            }
            return res.Result;
        }
    }
}
